package com.client.listeners;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.client.GUIMonitor;
import com.client.answers.Answer;
import com.client.answers.LoginAnswer;
import com.client.answers.SimpleAnswer;
import com.client.gui.DoodleGuiTestMain;

public class JoinButtonListener implements ActionListener {
	private JList				roomList;
	private GUIMonitor			guim;
	private DoodleGuiTestMain	guiMain;
	private JPasswordField		passField;
	private JFrame				frame;

	public JoinButtonListener(DoodleGuiTestMain guiMain, JList list, GUIMonitor guim)
	{
		this.guiMain = guiMain;
		this.guim = guim;
		roomList = list;
		passField = new JPasswordField(10);
		passField.setActionCommand("OK");
		passField.addActionListener(this);

	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		guim.setAnswer(GUIMonitor.JOIN_OR_CREATE_ACTION, new SimpleAnswer(Answer.JOIN));

		Object s = roomList.getSelectedValue();
		
		// System.out.println("S är: " + s.toString());
		if (s != null)
		{

			// Sets up "join room GUI"
			frame = new JFrame("Join room");
			frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			JLabel passLabel = new JLabel("Enter password:     ");

			JPanel passPanel = new JPanel();
			passPanel.add(passLabel);
			passPanel.add(passField);

			frame.setPreferredSize(new Dimension(300, 50));
			frame.getContentPane().add(passPanel);
			frame.setLocationRelativeTo(null);
			frame.setResizable(false);
			frame.pack();
			frame.setVisible(true);

			String cmd = e.getActionCommand();
			if (cmd.equals("OK"))
			{
				// Process the password.
				char[] passInput = passField.getPassword();
				String password = new String(passInput);
				
				// guim.setAnswer(GUIMonitor.ROOM_JOIN_ACTION, new LoginAnswer(0, "ojoj"));
				guim.setAnswer(GUIMonitor.ROOM_JOIN_ACTION, new LoginAnswer(roomList.getSelectedIndex(), password));
				System.out.println("har postat login info från join button");
				guiMain.enterDrawingState();

				Arrays.fill(passInput, '0');
				passField.setText("");

				// Framen st�ngs inte av om man har den i en if-sats....
				frame.setVisible(false);
				frame.dispose();
			}

		} else
		{
			System.out.println("s är 0");
		}

		// guim.setAnswer(GUIMonitor.ROOM_JOIN_ACTION, new LoginAnswer(0, "ojoj"));
		// System.out.println("har postat logni info från join button");
		// guiMain.enterDrawingState();
	}

}
